<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax</title>
    <link rel="stylesheet" href="./static/css/test.css">
</head>

<body>
    <div class="navigation">
        <div class="container">
            你好，请<a class="login">&nbsp;登录&nbsp;</a>\
            <a class="login">&nbsp;注册</a>
        </div>
    </div>
    <div class="tab">
        <table class="table-head">
            <thead class="tab-head">
                <tr>
                    <th><input type="checkbox" id="cheAll">全选</th>
                    <th>ID</th>
                    <th>名字</th>
                    <th>地址</th>
                    <th>排名</th>
                    <th>国家</th>
                </tr>
            </thead>
        </table>
        <div class="wrap">
            <table class="table-body">
                <tbody id="tbody">
                    <!-- <tr>
                    <td><input type="checkbox"></td>
                    <td>1</td>
                    <td>Google</td>
                    <td>https://www.google.cm/</td>
                    <td>1</td>
                    <td>USA</td>
                    <td>删除</td>
                </tr> -->
                </tbody>
            </table>
        </div>
        <table class="table-foot">
            <thead class="tab-foot">
                <tr id="control">
                    <th>已选择<span class="check">(0)</span></th>
                    <th id="add">添加</th>
                    <th id="del">删除</th>
                    <th id="modifi">修改</th>
                    <th id="JOSNP">JOSNP</th>
                </tr>
            </thead>
        </table>
    </div>
    <!-- 弹出层 -->
    <div class="modal">
        <div class="mask"></div>
        <div class="modal-body">
            <div class="modal-content">
            </div>
            <div class="control">
                <button class="submit" data-id="add">提交</button>
                <button class="cancel">取消</button>
            </div>
        </div>
    </div>
    </div>
    <script src="./static/jquery-3.5.1.js"></script>
    <script>
        $(function () {
            const basics = '';
            let PAGE_INDEX = 1
            let PAGE_SIZE = 0;
            let loading = false;
            function Ajax(page) {
                loading = true;
                $.ajax({
                    url: basics + '/websites/lists',
                    type: 'GET',
                    dataType: 'JSON',
                    data: {
                        page: 1,
                        pageSize: 20
                    },
                    success: function (msg, textStatus) {
                        loading = false
                        console.log(PAGE_SIZE, msg.data.length)
                        if (msg.data.length !== PAGE_SIZE) {
                            prevData = msg.data;
                            PAGE_SIZE = msg.data.length;
                            textStatus && render(msg)
                        } else {
                            PAGE_INDEX--
                            Prompt('已经是最后一页了')
                        }
                    },
                    error: function (xhr, status, err) {
                        loading = false
                        return err
                    }
                })
            }
            Ajax(PAGE_INDEX);
            // 加载页面
            function render(data) {
                data = data.data;
                let fragment = new DocumentFragment();
                let tbody = $('#tbody')
                tbody.html('')
                $(data).each(function (i, el) {
                    let tr = document.createElement('tr');
                    let store = [];
                    let id = '';
                    for (const key in el) {

                        let html = `<td>${el[key]}</td>`
                        if (key === 'id') {
                            id = el[key];
                        }
                        if (key === 'url') {
                            html = `<td class='url'>${el[key]}</td>`
                        }
                        store.push(html)
                    }
                    let td_check = `<td><input type="checkbox" data-index="${id}" class="che"></td>`
                    store.unshift(td_check)
                    tr.innerHTML = store.join('');
                    fragment.append(tr)
                })
                tbody.append(fragment)
                init(data.length)
            }

            // 初始化 ==============================================================
            function init(len) {
                // 数据初始化
                initTabFoot(len)
                // 绑定事件
                // 单选框
                OnChecked(len)
                // 全选框
                OnCheckedAll(len)
            }

            // 初始化TabFoot数据
            function initTabFoot(len) {
                $('.check').html(`(0)`)
            }
            // 事件绑定 ==================================================================
            $('#control').on('click', 'th', function () {
                // 弹窗事件
                let id = ['add', 'del', 'modifi'];
                if (id.includes(this.id)) {
                    $('.modal').addClass('show')
                    $('.control').attr('data-control', this.id)
                    modalShow[this.id]()
                } else if (this.id === 'JOSNP') {
                    $.ajax({
                        url: basics + '/websites/lists',
                        type: 'GET',
                        dataType: 'JSONP',
                        data: {
                            page: 1,
                            pageSize: PAGE_SIZE
                        },
                        success: callback
                    })
                    Prompt('JOSNP调用成功！')
                }

            })
            // 滚动事件
            $('.wrap').scroll(function () {
                let top = this.scrollTop;
                let height = this.scrollHeight;
                let tall = Math.round($(this).height());
                if (top + tall === height) {
                    if(loading) return;
                    PAGE_INDEX++
                    Page(PAGE_INDEX)
                }
            })
            // 显示弹窗
            const modalShow = {
                add: function () {
                    let html = `<h4 class="modal-title">请输入你要添加的信息</h4>
                    <div class="modal-row">
                        <span>名字:</span>
                        <input type="text" name="name">
                    </div>
                    <div class="modal-row">
                        <span>地址:</span>
                        <input type="text" name="url">
                    </div>
                    <div class="modal-row">
                        <span>排名:</span>
                        <input type="text" name="alexa">
                    </div>
                    <div class="modal-row">
                        <span>国家:</span>
                        <input type="text" name="country">
                    </div>`;
                    $('.modal-content').html(html)
                },
                del: function () {
                    let len = $('.che:checked').length;
                    let html = '';
                    if (len) {
                        html = `<h4 class="modal-title">你选择了${len}条数据,确定要删除吗？</h4>`;
                        $('.modal-content').html(html)
                    } else {
                        Prompt('你还么有勾选任何列表')
                    }
                },
                modifi: function () {
                    let html = `<h4 class="modal-title">请输入你要修改的信息</h4>
                                         <div class="modal-row">
                                             <span>ID:</span>
                                             <input type="text" name="ID">
                                         </div>
                                        <div class="modal-row">
                                            <span>名字:</span>
                                            <input type="text" name="name">
                                        </div>
                                        <div class="modal-row">
                                            <span>地址:</span>
                                            <input type="text" name="url">
                                        </div>
                                        <div class="modal-row">
                                            <span>排名:</span>
                                            <input type="text" name="alexa">
                                        </div>
                                        <div class="modal-row">
                                            <span>国家:</span>
                                            <input type="text" name="country">
                            </div>`;
                    $('.modal-content').html(html)
                },
            }
            // 取消弹窗
            $('.cancel').on('click', function () {
                $(this).parents().removeClass('show')
                $('.modal-content').html('')
                $('.control').removeAttr('data-control')
            })
            // input单选框
            function OnChecked(len) {
                let $table = $('.table-body')
                let checked = $('.checkbox')
                let flag = false;
                $table.on('change', 'input', function () {
                    let checkedLen = $('.che:checked').length;
                    $('.check').html(`(${checkedLen})`)
                    if (checkedLen === len) {
                        flag = true
                    } else {
                        flag = false
                    }
                    $('#cheAll').prop('checked', flag)
                })
            }
            // input全选框
            function OnCheckedAll(len) {
                let cheAll = $('#cheAll')
                // prop => property
                // attr => attribute ttttttil
                cheAll.prop('checked', false)
                cheAll.on('change', function () {
                    $('.che').prop('checked', this.checked)
                    let checkedLen = $('.che:checked').length;
                    $('.check').html(`(${checkedLen})`)
                })
            }
            // 翻页
            function Page(page) {
                Ajax(page)
            }
            // 增删改查 =================================================
            $('.submit').on('click', function () {
                let target = $(this).parent().attr('data-control')
                // 增 ==============================================
                if (target === 'add') {
                    let input = $(this).parent().prev().find('input')
                    let dataObj = mapDate(input);
                    dataChange[target](dataObj);
                    // 删 ==========================================
                } else if (target === 'del') {
                    $('.che:checked').each(function (i, el) {
                        let dataID = mapID($(el))
                        dataChange[target](dataID);
                    })
                    // 改 ==========================================
                } else if (target === 'modifi') {
                    let input = $(this).parent().prev().find('input')
                    let dataObj = mapDate(input);
                    dataChange[target](dataObj);
                }

                $(this).parents().removeClass('show')
                $('.modal-content').html('')
            })
            // 收集数据
            function mapDate(node) {
                const data = {};
                node.each(function (i, el) {
                    let key = $(el).attr('name')
                    if ($(el).val().length > 0) {
                        data[key] = $(el).val()
                    } else {
                        return prompt(key + '不能为空')
                    }
                })
                return data
            }
            // 收集id
            function mapID(node) {
                let data = {};
                data['id'] = node.attr('data-index')
                return data
            }
            const dataChange = {
                add: function (option) {
                    $.ajax({
                        url: basics + '/websites/add',
                        type: 'POST',
                        dataType: 'JSON',
                        data: {
                            name: option.name,
                            url: option.url,
                            alexa: option.alexa,
                            country: option.country
                        },
                        success: function (msg, textStatus) {
                            Ajax(PAGE_INDEX);
                        }
                    })

                },
                del: function (option) {
                    $.ajax({
                        url: basics + '/websites/delete',
                        type: 'delete',
                        dataType: 'JSON',
                        data: {
                            id: option.id
                        },
                        success: function (msg, textStatus) {
                            Ajax(PAGE_INDEX);
                        }
                    })

                },
                modifi: function (option) {
                    $.ajax({
                        url: basics + '/websites/update',
                        type: 'POST',
                        dataType: 'JSON',
                        data: {
                            id: option.ID,
                            name: option.name,
                            url: option.url,
                            alexa: option.alexa,
                            country: option.country
                        },
                        success: function () {
                            Ajax(PAGE_INDEX);
                        }
                    })
                }
            }
            // 提示框
            function Prompt(msg) {
                $('.modal').addClass('show')
                $('.control').hide()
                let div = document.createElement('div')
                div.className = 'Prompt';
                $(div).html(msg)
                $('.modal-content').append($(div))

                setTimeout(function () {
                    $('.modal-content').html('')
                    $('.control').show()
                    $('.modal').removeClass('show')
                }, 800)
            }

            function callback(msg) {
                msg = JSON.stringify(msg.data)
                alert(msg)
            }
        })
    </script>
</body>

</html>